package com.navinfo.tripanalysis.common.arithmetic;

import com.google.common.base.Joiner;
import com.navinfo.tripanalysis.common.arithmetic.common.CommonData;
import com.navinfo.tripanalysis.common.arithmetic.common.InterCrossCity;
import com.navinfo.tripanalysis.common.arithmetic.common.OuterStatisticData;
import com.navinfo.tripanalysis.common.arithmetic.custom.VarCrossCity;
import com.navinfo.tripanalysis.common.arithmetic.manager.AbstractArithmetic;
import com.navinfo.tripanalysis.common.util.ArithmeticUtils;

import java.util.Set;

/**
 * 经过城市算法<br/>
 * 依赖里程油耗算法{@link Mileage}<br/>
 * 输出：统计<br/>
 */
public class CrossCity extends AbstractArithmetic<VarCrossCity> {

    @Override
    public void calculate() {
        logger.debug("进入经过城市算法.");

        if(null != drivingData.getTileLcBroadcast()){
            VarCrossCity var = getObj();
            CommonData commonData = getCommonData();

            //根据经纬度获取区域编码
            Integer currentLc = ArithmeticUtils.getLc(commonData.getOriginalLat(), commonData.getOriginalLng(), drivingData.getTileLcBroadcast().getValue());
            if(currentLc != null){
                //加入城市编码去重列表
                var.getCityCodes().add(currentLc);

                //上一个城市为null，或者上个城市和当前城市不一致，加入城市详情
                InterCrossCity preCrossCity = var.getPreCrossCity();
                InterCrossCity currentCrossCity = currentCrossCity(commonData, currentLc);
                if(preCrossCity == null || currentCrossCity.getLcid() != preCrossCity.getLcid()){
                    var.getCrossCitiesDetail().add(currentCrossCity);
                }

                var.setPreCrossCity(currentCrossCity);
            }
        }

        logger.debug("离开经过城市算法.");
    }

    /**
     * 创建当前经过城市信息
     * @param commonData
     * @param currentLc
     */
    private InterCrossCity currentCrossCity(CommonData commonData, Integer currentLc) {
        InterCrossCity crossCity = new InterCrossCity();
        crossCity.setLcid(currentLc);
        crossCity.setStime((int)(commonData.getGpsTime()/1000L));
        crossCity.setLatitude(commonData.getLatitude());
        crossCity.setLongitude(commonData.getLongitude());
        crossCity.setMileage((int)commonData.getIntegralMileage());
        crossCity.setFuel((int)commonData.getIntegralFuel());
        return crossCity;
    }

    @Override
    public void collect(OuterStatisticData statisticDataOut) {
        VarCrossCity var = getObj();
        Set<Integer> cityCodes = var.getCityCodes();
        statisticDataOut.setCrossCities(cityCodes.size()>0 ? Joiner.on(",").join(cityCodes.iterator()) : "");
        statisticDataOut.setCrossCitiesDetail(var.getCrossCitiesDetail());
    }
}